package com.itheima.service.mongo.impl;

import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.VisitorService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class VisitorServiceImpl implements VisitorService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询历史访客
     * @param userId 登陆用户id
     * @param lastTime 上次登陆时间
     * @return 访客集合
     */
    @Override
    public List<Visitor> findVisitorList(Long userId,String lastTime) {
        Query query = new Query(Criteria.where("userId").is(userId)
                                .and("date").gte(Long.valueOf(lastTime)))
                                .with(Sort.by(Sort.Order.desc("date")))
                                .skip(0).limit(4);
        return mongoTemplate.find(query, Visitor.class);
    }

    @Autowired
    private RecommendUserService recommendUserService;
    /**
     * 保存访问记录
     * @param loginUserId
     * @param visitorId
     * @param source
     */
    @Override
    public void saveVisitor(Long loginUserId, Long visitorId, String source) {

        if (loginUserId != visitorId) {
            System.out.println("保存历史记录");
            Query query = new Query(Criteria.where("userId").is(visitorId)
                    .and("visitorUserId").is(loginUserId));
            Visitor visitor = mongoTemplate.findOne(query, Visitor.class);
            if (visitor == null) {
                visitor = new Visitor();
                visitor.setUserId(visitorId);//被访问者
                visitor.setVisitorUserId(loginUserId);//访问者
                visitor.setDate(System.currentTimeMillis());
                RecommendUser user = recommendUserService.findFateValue(loginUserId, visitorId);
                if (user != null) {
                    visitor.setScore(user.getScore());
                } else {
                    visitor.setScore(RandomUtil.randomDouble(66,99));
                }

                visitor.setFrom(source);
            } else {
                visitor.setDate(System.currentTimeMillis());
            }
            System.out.println("访问者:"+visitor);
            mongoTemplate.save(visitor);
        }
    }
}
